package com.lagou.rpc.consumer.proxy;

import com.lagou.rpc.consumer.annotation.Remote;
import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class RemoteServiceBeanPostProcessor implements BeanPostProcessor {
    @Autowired
    private RemoteServiceProxyFactory proxyFactory;

    @SneakyThrows
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //通过反射获取bean对象的属性
        Class targetClass = bean.getClass();
        Field[] fields = targetClass.getDeclaredFields();
        for (Field field : fields) {
            //找到标有Remote注解的字段
            boolean annotationPresent = field.isAnnotationPresent(Remote.class);
            if(annotationPresent){
                if(!field.getType().isInterface()){
                    throw new BeanCreationException("Class:"+bean.getClass().getSimpleName()
                            +" field "+field.getName()+" must be an interface");
                }

                field.setAccessible(Boolean.TRUE);

                try {
                    field.set(bean, proxyFactory.createProxy(field.getType()));
                }
                catch (Exception ignore){}
            }
        }
        return bean;
    }
}
